﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Linq.Dynamic;
using System.ComponentModel;

namespace Sunny.Controls
{
	/// <summary>
	/// GridPanel.xaml 的交互逻辑
	/// </summary>
	public partial class GridPanel : DockPanel, System.ComponentModel.INotifyPropertyChanged
	{
		public event PropertyChangedEventHandler PropertyChanged;
		protected virtual void OnPropertyChanged(string name)
		{
			this.PropertyChanged(this, new PropertyChangedEventArgs(name));
		}

		public string DataKeyName { get; set; }

		private Telerik.Windows.Controls.GridViewColumn _SelectColumn;
		protected Telerik.Windows.Controls.GridViewColumn SelectColumn
		{
			get
			{
				if (this._SelectColumn == null)
					this._SelectColumn = (Telerik.Windows.Controls.GridViewColumn)this.FindResource("SelectColumn");
				return this._SelectColumn;
			}
		}

		protected CheckBox SelectAllCheckBox
		{
			get
			{
				return (CheckBox)((WrapPanel)this.SelectColumn.Header).Children[0];
			}
		}

		protected CheckBox SelectCurrentPageCheckBox
		{
			get
			{
				return (CheckBox)((WrapPanel)this.SelectColumn.Header).Children[1];
			}
		}

		public bool ShowSelector
		{
			get
			{
				return this.SelectColumn.IsVisible;
			}
			set
			{
				this.SelectColumn.IsVisible = value;
			}
		}

		public object[] SelectedDataKeyValues
		{
			get
			{
				if (this.SelectAllCheckBox.IsChecked == true)
				{
					System.Collections.Generic.List<object> values = ((System.Linq.IQueryable)this.Pager.Source).Select(this.DataKeyName).OfType<object>().ToList();
					foreach (object value in this.UserSelectedDataKeyValues)
						values.Remove(value);
					return values.ToArray();
				}
				else return this.UserSelectedDataKeyValues.ToArray();
			}
		}

		//public bool SelectAllChecked
		//{
		//	get { return (bool)GetValue(SelectAllCheckedProperty); }
		//	set { SetValue(SelectAllCheckedProperty, value); }
		//}
		//public static readonly DependencyProperty SelectAllCheckedProperty =
		//	DependencyProperty.Register("SelectAllChecked", typeof(bool), typeof(GridPanel), new PropertyMetadata(false));

		public System.Collections.Generic.List<object> UserSelectedDataKeyValues = new List<object>();


		protected Searcher.WhereCommand Where;

		protected string Order;

		//public Sunny.Controls.Toolbar Toolbar
		//{
		//	get
		//	{
		//		return this._Toolbar;
		//	}
		//}

		//public Telerik.Windows.Controls.RadGridView Grid
		//{
		//	get
		//	{
		//		return this._Grid;
		//	}
		//}

		protected bool AllowPaging = true;

		System.Collections.Generic.List<CheckBox> CheckBoxesInCurrentPage = new List<CheckBox>();

		public Toolbar Toolbar
		{
			get { return (Toolbar)GetValue(ToolbarProperty); }
			set
			{
				SetValue(ToolbarProperty, value);
				this.OnPropertyChanged("Toolbar");
			}
		}
		public static readonly DependencyProperty ToolbarProperty = DependencyProperty.Register("Toolbar", typeof(Toolbar), typeof(Toolbar), new PropertyMetadata(null));

		public Telerik.Windows.Controls.RadGridView Grid
		{
			get { return (Telerik.Windows.Controls.RadGridView)GetValue(GridProperty); }
			set
			{
				SetValue(GridProperty, value);
				this.OnPropertyChanged("Grid");
				value.Columns.Insert(0, this.SelectColumn);
			}
		}
		public static readonly DependencyProperty GridProperty = DependencyProperty.Register("Grid", typeof(Telerik.Windows.Controls.RadGridView), typeof(Telerik.Windows.Controls.RadGridView), new PropertyMetadata(null));

		//public System.Windows.Controls.UIElementCollection ToolbarItems
		//{
		//	get
		//	{
		//		return this.Toolbar.Items;
		//	}
		//}

		//public Searcher.SimpleSearcher Searcher
		//{
		//	get
		//	{
		//		return this.Toolbar.Searcher;
		//	}
		//}

		//public Telerik.Windows.Controls.GridViewColumnCollection Columns
		//{
		//	get
		//	{
		//		return this.Grid.Columns;
		//	}
		//}

		public GridPanel()
		{
			InitializeComponent();
		}

		public System.Linq.IQueryable GetDataSource(ToolbarQueryAction action)
		{
			return this.GetDataSource(action, true);
		}

		public System.Linq.IQueryable GetDataSource(ToolbarQueryAction action, bool order)
		{
			System.Linq.IQueryable dataSource = this.OnNeedDataSource(action);
			if (this.Where != null)
				dataSource = dataSource.Where(this.Where.Text, this.Where.Parameters);
			if (order)
				if (!string.IsNullOrEmpty(this.Order))
					dataSource = dataSource.OrderBy(this.Order);
			return dataSource;
		}

		public event System.EventHandler<NeedDataSourceEventArgs> NeedDataSource;

		protected System.Linq.IQueryable OnNeedDataSource(ToolbarQueryAction action)
		{
			if (this.NeedDataSource == null)
				return null;
			NeedDataSourceEventArgs args = new NeedDataSourceEventArgs(action);
			this.NeedDataSource(this, args);
			return args.DataSource;
		}

		public void BindGrid()
		{
			this.BindGrid(ToolbarQueryAction.Search);
		}

		public void BindGrid(ToolbarQueryAction action)
		{
			System.Linq.IQueryable dataSource = this.GetDataSource(action);

			if (this.AllowPaging)
				this.Pager.PageSize = (int)(this.Grid.ActualHeight- 25) / (int)this.Grid.RowHeight;
			else this.Pager.PageSize = int.MaxValue;

			this.Pager.Source = dataSource;
			//	this.Grid.ItemsSource = dataSource.Skip(this.Pager.PageSize * this.Pager.PageIndex).Take(this.Pager.PageSize).OfType<object>().ToArray();
			//else this.Grid.ItemsSource = dataSource.OfType<object>().ToArray();
		}

		private void Grid_SizeChanged(object sender, SizeChangedEventArgs e)
		{
			this.Pager.PageIndex = 0;
			this.BindGrid();
		}

		private void Grid_Sorting(object sender, Telerik.Windows.Controls.GridViewSortingEventArgs e)
		{

		}

		private void SelectAllCheckBox_Changed(object sender, RoutedEventArgs e)
		{
			this.SelectAllCheckBox.Tag = true;
			this.SelectCurrentPageCheckBox.IsChecked = this.SelectAllCheckBox.IsChecked;
			this.UserSelectedDataKeyValues = new List<object>();
			this.SelectAllCheckBox.Tag = null;
		}

		private void SelectCurrentPageCheckBox_Changed(object sender, RoutedEventArgs e)
		{
			foreach (CheckBox checkBox in this.CheckBoxesInCurrentPage)
				checkBox.IsChecked = ((CheckBox)sender).IsChecked;
		}

		private void CheckBox_Changed(object sender, RoutedEventArgs e)
		{
			if (this.SelectAllCheckBox.Tag != null)
				return;

			CheckBox checkBox = (CheckBox)sender;
			if (!checkBox.IsLoaded)
				return;

			if ((this.SelectAllCheckBox.IsChecked == false && checkBox.IsChecked == true) || (this.SelectAllCheckBox.IsChecked == true && checkBox.IsChecked == false))
				this.UserSelectedDataKeyValues.Add(checkBox.Tag);
			else this.UserSelectedDataKeyValues.Remove(checkBox.Tag);
		}

		private void CheckBox_Loaded(object sender, RoutedEventArgs e)
		{
			if (this.DataKeyName == null)
				return;

			CheckBox checkBox = (CheckBox)sender;
			checkBox.IsEnabled = false;
			this.CheckBoxesInCurrentPage.Add(checkBox);
			checkBox.Tag = checkBox.DataContext.GetType().GetProperty(this.DataKeyName).GetValue(checkBox.DataContext, null);
			if (this.SelectAllCheckBox.IsChecked == true)
				checkBox.IsChecked = !this.UserSelectedDataKeyValues.Contains(checkBox.Tag);
			else checkBox.IsChecked = this.UserSelectedDataKeyValues.Contains(checkBox.Tag);
			checkBox.IsEnabled = true;
		}

		private void CheckBox_Unloaded(object sender, RoutedEventArgs e)
		{
			this.CheckBoxesInCurrentPage.Remove((CheckBox)sender);
		}

		protected Searcher.WhereCommand ExportParameter;

		private void Toolbar_Query(object sender, QueryEventArgs e)
		{
			//this.SelectAllChecked = false;

			if (e.Action == ToolbarQueryAction.Export)
				this.AllowPaging = false;
			else
			{
				this.Where = e.WhereCommand;
				this.Order = e.OrderCommand;
			}
			this.Pager.PageIndex = 0;
			this.BindGrid(e.Action);
			if (e.Action != ToolbarQueryAction.Export)
				return;
			this.ExportParameter = e.WhereCommand;
		}

		private void Toolbar_Reload(object sender, RoutedEventArgs e)
		{
			if (!e.Handled)
				this.BindGrid();
		}

		private void Toolbar_Export(object sender, RoutedEventArgs e)
		{
			if (e.Handled)
				return;

			this.AllowPaging = false;
			this.BindGrid();

			this.Grid.Export(System.IO.File.OpenWrite("C:\\Test.xls"), new Telerik.Windows.Controls.GridViewExportOptions { Format = Telerik.Windows.Controls.ExportFormat.ExcelML });

			this.AllowPaging = true;
			this.BindGrid();
		}

		private void FirstPage_Click(object sender, RoutedEventArgs e)
		{
			this.Pager.MoveToFirstPage();
		}

		private void PreviousPage_Click(object sender, RoutedEventArgs e)
		{
			this.Pager.MoveToPreviousPage();
		}

		private void NextPage_Click(object sender, RoutedEventArgs e)
		{
			this.Pager.MoveToNextPage();
		}

		private void LastPage_Click(object sender, RoutedEventArgs e)
		{
			this.Pager.MoveToLastPage();
		}

		private void GoToPage_Click(object sender, RoutedEventArgs e)
		{
			double? index = ((Telerik.Windows.Controls.RadNumericUpDown)((WrapPanel)((Sunny.Controls.Button)sender).Parent).FindName("GoToIndex")).Value;
			if (index == null)
				return;
			if (!this.Pager.MoveToPage((int)index.Value - 1))
				MessageBox.Show("无法跳转到指定的页码！", "页面跳转失败", MessageBoxButton.OK, MessageBoxImage.Error);
		}
	}
}
